package com.incross.dawin.views;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.incross.dawin.DawinConfig;
import com.incross.dawin.util.BKImageDownloader;
import com.incross.dawin.util.BKImageDownloader.OnDownloadFinishListener;
import com.incross.dawin.util.BKImageDownloaderTask;
import com.incross.dawin.util.BKLog;
import com.incross.dawin.util.CommonUtils;
import com.incross.dawin.util.CommonUtils.ScreenSize;

public class BKDialog extends Activity implements OnClickListener, OnDownloadFinishListener, OnTouchListener {
	public static final String KEY_LANDING_PAGE_URL = "key_landingpage_url";
	public static final String KEY_LANDING_PAGE_TITLE = "key_landingpage_title";
	public static final String KEY_LANDING_PAGE_REAL_URL = "key_landingpage_real_url";
	
	public static final int ACTION_CLICKVIEWER = 190293;
	
	private final int SPINNER_LAYOUT = 100;
	private final int BROWSER_LAYOUT = 200;
	
	private String mUrl, mRealUrl;
	
	private Activity mActivity;
	
	private ImageButton mBackButton, mForwardButton, mRefreshButton, mShareButton, mCloseButton;
	private WebView mWebView;
	
	private LinearLayout mBrowserLayout;
	private LinearLayout.LayoutParams mBrowserLayoutParam;
	
//	private LinearLayout mSpinnerLayout;
//	private ProgressBar mProgress;
	
	private int mMarginRate = 0;
	
	private int mCurrentOrientation;
	
	private int mDownloadCount = 0;
	private int mDownloadedCount = 7;
	
	private int mButtonLayoutHeight = 100;
	private boolean mIsButtonLayoutHeightSet = false;
	
	private boolean mIsBackExists = false, mIsForwardExists = false, mIsRefreshExists = false, mIsSendExists = false, mIsCloseExists = false;
	private boolean mIsBgSelExists = false, mIsBgNorExists = false;
	
	private Bitmap mBackImg, mForwardImg, mRefreshImg, mSendImg, mCloseImg, mBgSelImg, mBgNorImg;
	
	private String mTitle;
	
	private BKImageDownloader mImageDownloader;
	
	private boolean mIsShowing = false;
	
	private OnDialogStateListener mListener;
	
	public interface OnDialogStateListener {
		public abstract void onDialogShown();
		public abstract void onDialogDismissed();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActivity = this;
		// Trick of hide status bar
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		mImageDownloader = new BKImageDownloader(this);
		
		mUrl = getIntent().getStringExtra(KEY_LANDING_PAGE_URL);
		mRealUrl = getIntent().getStringExtra(KEY_LANDING_PAGE_REAL_URL);
		mTitle = getIntent().getStringExtra(KEY_LANDING_PAGE_TITLE);
		if(mUrl == null || mUrl.equals("")) {
			dismiss();
		}
		
		if(mTitle == null || mTitle.equals("")) {
			mTitle = "Shared Url";
		}
		initViews();
		if(isImageExists()) {
			setButtonImages();
			/*switchLayout(BROWSER_LAYOUT);*/
		}
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
		BKLog.d("Dialog", "onResume");
		if(mListener != null) {
			mListener.onDialogShown();
		}
		
		mIsShowing = true;
	}
	
	@Override
	public void onPause() {
		super.onPause();
		BKLog.d("Dialog", "onPause");
		mIsShowing = false;
	}
	
	@Override
	public void onBackPressed() {
		dismiss();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		if(mWebView != null) {
			mWebView.stopLoading();
			mWebView.removeAllViews();
			mWebView.clearView();
			mWebView.clearCache(true);
			mWebView.clearHistory();
			mWebView.clearFormData();
			mWebView.destroy();
		}
		System.gc();
		BKLog.d("Dialog", "onDestroy");
	}
	
	public void setOnDialogStateListener(OnDialogStateListener l) {
		mListener = l;
	}
	
	private boolean isImageExists() {
		if(mImageDownloader.isExists(DawinConfig.IMG_BACK_URL)) {
			mIsBackExists = true;
			mDownloadedCount--;
			mBackImg = getBitmap(DawinConfig.IMG_BACK_URL);
		}
		if(mImageDownloader.isExists(DawinConfig.IMG_BG_NOR_URL)) {
			mIsBgNorExists = true;
			mDownloadedCount--;
			mBgNorImg = getBitmap(DawinConfig.IMG_BG_NOR_URL);
		}
		if(mImageDownloader.isExists(DawinConfig.IMG_BG_SEL_URL)) {
			mIsBgSelExists = true;
			mDownloadedCount--;
			mBgSelImg = getBitmap(DawinConfig.IMG_BG_SEL_URL);
		}
		if(mImageDownloader.isExists(DawinConfig.IMG_CLOSE_URL)) {
			mIsCloseExists = true;
			mDownloadedCount--;
			mCloseImg = getBitmap(DawinConfig.IMG_CLOSE_URL);
		}
		if(mImageDownloader.isExists(DawinConfig.IMG_FORWARD_URL)) {
			mIsForwardExists = true;
			mDownloadedCount--;
			mForwardImg = getBitmap(DawinConfig.IMG_FORWARD_URL);
		}
		if(mImageDownloader.isExists(DawinConfig.IMG_REFRESH_URL)) {
			mIsRefreshExists = true;
			mDownloadedCount--;
			mRefreshImg = getBitmap(DawinConfig.IMG_REFRESH_URL);
		}
		if(mImageDownloader.isExists(DawinConfig.IMG_SEND_URL)) {
			mIsSendExists = true;
			mDownloadedCount--;
			mSendImg = getBitmap(DawinConfig.IMG_SEND_URL);
		}
		
		if(mDownloadedCount != 0) {
			downloadImage();
			return false;
		} else {
			return true;
		}
	}
	
	private void downloadImage() {
		if(!mIsBackExists) {
			mImageDownloader.download(DawinConfig.IMG_BACK_URL);
		}
		 
		if(!mIsBgNorExists) {
			mImageDownloader.download(DawinConfig.IMG_BG_NOR_URL);
		}
		
		if(!mIsBgSelExists) {
			mImageDownloader.download(DawinConfig.IMG_BG_SEL_URL);
		}
		
		if(!mIsCloseExists) {
			mImageDownloader.download(DawinConfig.IMG_CLOSE_URL);
		}
		
		if(!mIsForwardExists) {
			mImageDownloader.download(DawinConfig.IMG_FORWARD_URL);
		}
		
		if(!mIsRefreshExists) {
			mImageDownloader.download(DawinConfig.IMG_REFRESH_URL);
		}
		
		if(!mIsSendExists) {
			mImageDownloader.download(DawinConfig.IMG_SEND_URL);
		}
	}
	
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		BKLog.d("Dialog", "onConfigurationChanged");
		setBrowserLayoutSize();
	}
	
	public void dismiss() {
		if(mListener != null) {
			mListener.onDialogDismissed();
		}
		
		Intent intent = new Intent();
		setResult(RESULT_OK, intent);
		finish();
	}
	
	public boolean isShowing() {
		return mIsShowing;
	}
	
	private void setButtonImages() {
		mBackButton.setBackgroundDrawable(new BitmapDrawable(mBgNorImg));
		mBackButton.setImageBitmap(mBackImg);
		
		mForwardButton.setBackgroundDrawable(new BitmapDrawable(mBgNorImg));
		mForwardButton.setImageBitmap(mForwardImg);
		
		mRefreshButton.setBackgroundDrawable(new BitmapDrawable(mBgNorImg));
		mRefreshButton.setImageBitmap(mRefreshImg);
		
		mShareButton.setBackgroundDrawable(new BitmapDrawable(mBgNorImg));
		mShareButton.setImageBitmap(mSendImg);
		
		mCloseButton.setBackgroundDrawable(new BitmapDrawable(mBgNorImg));
		mCloseButton.setImageBitmap(mCloseImg);
	}
	
	
	private void initViews() {
//		WindowManager.LayoutParams windowManager = getWindow().getAttributes();
//		windowManager.dimAmount = 0.75f;
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
//		
//		getWindow().setGravity(Gravity.CENTER);
		
//		mProgress = new ProgressBar(this, null, android.R.attr.progressBarStyle);
		setBrowserLayoutSize();
		mBrowserLayout.setVisibility(View.VISIBLE);
		LinearLayout mainLayout = new LinearLayout(this);
		LinearLayout.LayoutParams mainLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT, 1.0f);
		
		
		mainLayout.setGravity(Gravity.CENTER);
		
		
		
		
		// Web view area
		mWebView = new WebView(mActivity);
		getWindow().requestFeature(Window.FEATURE_PROGRESS);
		
		mWebView.getSettings().setBuiltInZoomControls(false);
		mWebView.getSettings().setJavaScriptEnabled(true);
		// 0 - Mobile, 1 - Desktop
		mWebView.getSettings().setUserAgent(0);
		
		//20131022 클릭뷰어에서 뜨는 웹뷰의 user agent에 구분자 넣는 부분 추가함 -- 모바일용 user agent 설정 후 첨부하는 것으로 변경
		String userAgent = (mWebView.getSettings().getUserAgentString() != null?"[Dawin Library for Android/Linux] " + mWebView.getSettings().getUserAgentString():"[Dawin Library for Android/Linux]");
		mWebView.getSettings().setUserAgentString(userAgent);
		BKLog.e("############### Webview userAgent : " + userAgent);
		
		// adjust screen size --> wideViewPort true -> double tab zoom in/out
		mWebView.getSettings().setUseWideViewPort(true);
		mWebView.setInitialScale(0);
		
		
		// block preload browser
		mWebView.setWebViewClient(new WebViewClient() {
			@Override
	        public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.e("BenTag", "WebView url = " + url);
				if(url.startsWith("market://")) {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.addCategory(Intent.CATEGORY_DEFAULT);
					intent.setData(Uri.parse(url));
					startActivity(intent);
					return true;
				} /*else if(url.startsWith("tstore://")) {
					Toast.makeText(mActivity, "티스토어 연결!!" + url, Toast.LENGTH_SHORT).show();
					BKLog.e("티스토어 url : " + url);
					
					String keyword = url.substring(9);
					BKLog.e("keyword : " + keyword);
					Intent intent = new Intent();
					intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
					intent.setClassName("com.skt.skaf.A000Z00040",  "com.skt.skaf.A000Z00040.A000Z00040");
					intent.setAction("COLLAB_ACTION");
					intent.putExtra("com.skt.skaf.COL.URI", keyword.getBytes());
					intent.putExtra("com.skt.skaf.COL.REQUESTER", "A000Z00040");
					startActivity(intent);
					
					return true;
				}*/
				
	            return (false);
	        }
			
			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				Toast.makeText(mActivity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
			}
			
			@Override
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
				// TODO Auto-generated method stub
				handler.proceed();
			}
			
		});
		
		mWebView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged (WebView view, int newProgress) {
			     // Activities and WebViews measure progress with different scales.
			     // The progress meter will automatically disappear when we reach 100%
			     mActivity.setProgress(newProgress * 1000);
			}
		});
		
		mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
		mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		mWebView.getSettings().setAppCacheEnabled(false);
//		mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		
		LinearLayout.LayoutParams webViewParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 0, 1.0f);
		webViewParam.gravity = Gravity.CENTER;
		
		// Bottom button area
		LinearLayout buttonLayout = new LinearLayout(this);
		buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
		
		LinearLayout.LayoutParams buttonLayoutParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, mButtonLayoutHeight, 0f);
		buttonLayoutParam.gravity = Gravity.CENTER;
		
		LinearLayout.LayoutParams buttonParam = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.FILL_PARENT, 1.0f);
		buttonParam.gravity = Gravity.CENTER;
		
		mBackButton = new ImageButton(this);
		mBackButton.setOnTouchListener(this);
		mForwardButton = new ImageButton(this);
		mForwardButton.setOnTouchListener(this);
		mRefreshButton = new ImageButton(this);
		mRefreshButton.setOnTouchListener(this);
		mShareButton = new ImageButton(this);
		mShareButton.setOnTouchListener(this);
		mCloseButton = new ImageButton(this);
		mCloseButton.setOnTouchListener(this);
		
		buttonLayout.addView(mBackButton, buttonParam);
		buttonLayout.addView(mForwardButton, buttonParam);
		buttonLayout.addView(mRefreshButton, buttonParam);
		buttonLayout.addView(mShareButton, buttonParam);
		buttonLayout.addView(mCloseButton, buttonParam);
		
		
		mBrowserLayout.addView(mWebView, webViewParam);
		mBrowserLayout.addView(buttonLayout, buttonLayoutParam);
		
		mainLayout.addView(mBrowserLayout, mBrowserLayoutParam);
		
//		mSpinnerLayout.addView(mProgress);
//		mainLayout.addView(mSpinnerLayout, mBrowserLayoutParam);
		
		setContentView(mainLayout, mainLayoutParams);
		
		/*map url test address : "https://maps.google.co.kr/?source=friendlink&q=37.385126,127.111423(%EB%82%B4+%EC%9C%84%EC%B9%98%40%EC%98%A4%ED%9B%84+7:51,3/6)&z=17"*/
		if(mUrl != null) mWebView.loadUrl(mUrl);
		mWebView.setDownloadListener(new DownloadListener() {
		    
		    @Override
		    public void onDownloadStart(String url, String userAgent,
		      String contentDisposition, String mimeType, long contentLength) {
		     
//		     Log.d("MAIL", "url : " + url);
//		     Log.d("MAIL", "userAgent : " + userAgent);
//		     Log.d("MAIL", "contentDisposition : " + contentDisposition);
//		     Log.d("MAIL", "mimeType : " + mimeType);
//		     Log.d("MAIL", "contentLength : " + contentLength);
//		     
//		              downloadUpdateFile(url, contentDisposition, mimeType);
		    }
		   });
	}
	
	
	private void setBrowserLayoutSize() {
		if(mBrowserLayout == null) {
			mBrowserLayout = new LinearLayout(this);
			mBrowserLayout.setOrientation(LinearLayout.VERTICAL);
		}
		
		/*if(mSpinnerLayout == null) {
			mSpinnerLayout = new LinearLayout(this);
			mBrowserLayout.setOrientation(LinearLayout.VERTICAL);
			mSpinnerLayout.setGravity(Gravity.CENTER);
		}*/
		
		
		ScreenSize screenSize = CommonUtils.getScreenSize(this);
		
		int width = screenSize.getWidth();
		int height = screenSize.getHeight();
		
		BKLog.d("Dialog", "width : " + width + ", height : " + height);
		
		if(mMarginRate >= 0 && mMarginRate <= 50) {
			width = width - ((width / 100) * mMarginRate);
			height = height - ((height / 100) * mMarginRate);
		} else {
			// default 5% margin
			width = width * (95/100);
			height = height * (95/100);
		}
		
		BKLog.d("Dialog", "after --> width : " + width + ", height : " + height);
		
		if(!mIsButtonLayoutHeightSet) {
			mIsButtonLayoutHeightSet = true;
			if(width > height) {
				mButtonLayoutHeight = ((width/100)*9);
			} else {
				mButtonLayoutHeight = ((height/100)*9);
			}
			BKLog.i("Dialog", "button layout height = " + mButtonLayoutHeight);
		}
		
		
		mBrowserLayoutParam = new LinearLayout.LayoutParams(width, height, 0f);
		
		mBrowserLayout.setLayoutParams(mBrowserLayoutParam);
		
//		mSpinnerLayout.setLayoutParams(mBrowserLayoutParam);
		
	}
	
	/*private void switchLayout(int what) {
		if(mBrowserLayout != null && mSpinnerLayout != null) {
			switch(what) {
				case SPINNER_LAYOUT:
					mBrowserLayout.setVisibility(View.GONE);
					mSpinnerLayout.setVisibility(View.VISIBLE);
					break;
					
				case BROWSER_LAYOUT:
					mBrowserLayout.setVisibility(View.VISIBLE);
					mSpinnerLayout.setVisibility(View.GONE);
					break;
			}
		}
	}*/
	
	private Bitmap getBitmap(String path) {
		String cachePath;
		if(CommonUtils.getStringPreference(this, "cache_path_new").equals("")) {
			cachePath = this.getCacheDir().getAbsolutePath() + "/icon/";
			CommonUtils.setStringPreference(this, "cache_path_new", cachePath);
		} else {
			cachePath = CommonUtils.getStringPreference(this, "cache_path_new");
		}
		
		int index = path.lastIndexOf("/");
		String filename = path.substring(index + 1);
		
		return BKImageDownloaderTask.getBitmap(cachePath + filename);
	}
	
	

	@Override
	public void onClick(View v) {
		if(v.equals(mBackButton)) {
			Toast.makeText(this, "Back button", Toast.LENGTH_SHORT).show();
		} else if(v.equals(mForwardButton)) {
			Toast.makeText(this, "Forward button", Toast.LENGTH_SHORT).show();
		} else if(v.equals(mRefreshButton)) {
			Toast.makeText(this, "Refresh button", Toast.LENGTH_SHORT).show();
		} else if(v.equals(mShareButton)) {
			Toast.makeText(this, "Send button", Toast.LENGTH_SHORT).show();
		} else if(v.equals(mCloseButton)) {
			Toast.makeText(this, "Finish.. bye...", Toast.LENGTH_SHORT).show();
			dismiss();
		}
	}


	@Override
	public void onDownloadFinished(boolean result, String requestedUrl) {
		mDownloadCount++;
		if(requestedUrl.equals(DawinConfig.IMG_BACK_URL)) {
			mIsBackExists = result;
			if(result) {
				mBackImg = getBitmap(DawinConfig.IMG_BACK_URL);
			}
		} else if(requestedUrl.equals(DawinConfig.IMG_BG_NOR_URL)) {
			mIsBgNorExists = result;
			if(result) {
				mBgNorImg = getBitmap(DawinConfig.IMG_BG_NOR_URL);
			}
		} else if(requestedUrl.equals(DawinConfig.IMG_BG_SEL_URL)) {
			mIsBgSelExists = result;
			if(result) {
				mBgSelImg = getBitmap(DawinConfig.IMG_BG_SEL_URL);
			}
		} else if(requestedUrl.equals(DawinConfig.IMG_CLOSE_URL)) {
			mIsCloseExists = result;
			if(result) {
				mCloseImg = getBitmap(DawinConfig.IMG_CLOSE_URL);
			}
		} else if(requestedUrl.equals(DawinConfig.IMG_FORWARD_URL)) {
			mIsForwardExists = result;
			if(result) {
				mForwardImg = getBitmap(DawinConfig.IMG_FORWARD_URL);
			}
		} else if(requestedUrl.equals(DawinConfig.IMG_REFRESH_URL)) {
			mIsRefreshExists = result;
			if(result) {
				mRefreshImg = getBitmap(DawinConfig.IMG_REFRESH_URL);
			}
		} else if(requestedUrl.equals(DawinConfig.IMG_SEND_URL)) {
			mIsSendExists = result;
			if(result) {
				mSendImg = getBitmap(DawinConfig.IMG_SEND_URL);
			}
		}
		
		if(mDownloadedCount == mDownloadCount) {
			if(isImageExists()) {
				setButtonImages();
				/*switchLayout(BROWSER_LAYOUT);*/
			}
			
			
			
		}
	}
	
	public int setMargin(int marginRate) {
		if(marginRate > 50 || marginRate < 0) {
			return -1;
		}
		mMarginRate = marginRate;
		return 0;
		
	}


	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if(v.equals(mBackButton)) {
			if(event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundDrawable(new BitmapDrawable(mBgSelImg));
			}
			else if(event.getAction() == MotionEvent.ACTION_UP){
				v.setBackgroundDrawable(new BitmapDrawable(mBgNorImg));
				if(mWebView.canGoBack()) {
					mWebView.goBack();
				}
			}
		} else if(v.equals(mForwardButton)) {
			if(event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundDrawable(new BitmapDrawable(mBgSelImg));
			}
			else if(event.getAction() == MotionEvent.ACTION_UP){
				v.setBackgroundDrawable(new BitmapDrawable(mBgNorImg));
				Toast.makeText(this, "Forward button", Toast.LENGTH_SHORT).show();
				if(mWebView.canGoForward()) {
					mWebView.goForward();
				}
			}
		} else if(v.equals(mRefreshButton)) {
			if(event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundDrawable(new BitmapDrawable(mBgSelImg));
			}
			else if(event.getAction() == MotionEvent.ACTION_UP){
				v.setBackgroundDrawable(new BitmapDrawable(mBgNorImg));
				mWebView.reload();
			}
		} else if(v.equals(mShareButton)) {
			if(event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundDrawable(new BitmapDrawable(mBgSelImg));
			}
			else if(event.getAction() == MotionEvent.ACTION_UP){
				if(mRealUrl != null || !mRealUrl.equals("")) {
					v.setBackgroundDrawable(new BitmapDrawable(mBgNorImg));
					Intent i = new Intent(Intent.ACTION_SEND);
					i.setType("text/plain");
					/*i.putExtra(Intent.EXTRA_SUBJECT, "");*/
					i.putExtra(Intent.EXTRA_TEXT, mRealUrl);
					startActivity(Intent.createChooser(i, "현재 페이지 공유"));
				} else {
					Toast.makeText(this, "페이지를 공유할 수 없습니다", Toast.LENGTH_SHORT).show();
				}
				
			}
			
		} else if(v.equals(mCloseButton)) {
			if(event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundDrawable(new BitmapDrawable(mBgSelImg));
			}
			else if(event.getAction() == MotionEvent.ACTION_UP){
				v.setBackgroundDrawable(new BitmapDrawable(mBgNorImg));
				dismiss();
			}
		}
		
		return false;
	}
	

}
